# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect
from miles.shortcuts import render


def form_save(request, form_class, template_name, extra_context={}, request_form=False,
              form_context_key='form', form_kwargs={}, save_kwargs={}, success_url=None):
    """
    Vista genérica con form. Si se envían los datos via post y son válidos se
    llama al metodo save() del form.
    """
    if request_form:
        form_kwargs['request'] = request
    if request.method == 'POST':
        form = form_class(request.POST, **form_kwargs)
        if form.is_valid():
            form.save(**save_kwargs)
            if not success_url:
                success_url = request.path
            return HttpResponseRedirect(success_url)
    else:
        form = form_class(**form_kwargs)
    context = {form_context_key: form}
    if extra_context:
        context.update(extra_context)
    return render(template_name, context, request)
